package com.atguigu.eduservice.service.impl;

import com.atguigu.commonutils.R;
import com.atguigu.eduservice.entity.*;
import com.atguigu.eduservice.entity.frontvo.CourseFrontVo;
import com.atguigu.eduservice.entity.frontvo.CourseWebVo;
import com.atguigu.eduservice.entity.vo.CourseInfoVo;
import com.atguigu.eduservice.entity.vo.CoursePublishVo;
import com.atguigu.eduservice.mapper.EduCourseMapper;
import com.atguigu.eduservice.service.EduChapterService;
import com.atguigu.eduservice.service.EduCourseDescriptionService;
import com.atguigu.eduservice.service.EduCourseService;
import com.atguigu.eduservice.service.EduVideoService;
import com.atguigu.servicebase.exceptionhandler.GuliException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2022-02-21
 */
@Service
public class EduCourseServiceImpl extends ServiceImpl<EduCourseMapper, EduCourse> implements EduCourseService {


    //引入EduCourseDescriptionService为了可以修改Description
    @Autowired
    private EduCourseDescriptionService eduCourseDescriptionService;

    //注入小节和章节service
    @Autowired
    private EduVideoService eduVideoService;

    @Autowired
    private EduChapterService eduChapterService;

    @Autowired
    private EduCourseService courseService;

    //添加课程基本信息的方法
    @Override
    public String saveCourseInfo(CourseInfoVo courseInfoVo) {
        //1向课程表添加课程基本信息
        EduCourse eduCourse = new EduCourse();
        BeanUtils.copyProperties(courseInfoVo, eduCourse);

        //insert为返回值，返回影响行数
        int insert = baseMapper.insert(eduCourse);
        if (insert == 0) {
            //添加失败
            throw new GuliException(20001, "添加课程信息失败");

        }

        String cid = eduCourse.getId();

        //2向课程简介表添加课程简介
        EduCourseDescription eduCourseDescription = new EduCourseDescription();
        eduCourseDescription.setDescription(courseInfoVo.getDescription());
        //设置描述id就是课程id
        eduCourseDescription.setId(cid);
        eduCourseDescriptionService.save(eduCourseDescription);
        return cid;
    }


    //根据课程id查询课程基本信息
    @Override
    public CourseInfoVo getCourseInfo(String courseId) {

        //1.查询课程表
        EduCourse eduCourse = baseMapper.selectById(courseId);
        CourseInfoVo courseInfoVo = new CourseInfoVo();
        BeanUtils.copyProperties(eduCourse, courseInfoVo);

        //2.查询描述表
        EduCourseDescription eduCourseDescription = eduCourseDescriptionService.getById(courseId);
        //2.1 将eduCourseDescription中查询出来的描述信息Description设置进courseInfoVo中
        courseInfoVo.setDescription(eduCourseDescription.getDescription());
        return courseInfoVo;


    }


    //修改课程信息
    @Override
    public void updateCourseInfo(CourseInfoVo courseInfoVo) {
        //1.修改课程表
        EduCourse eduCourse = new EduCourse();
        BeanUtils.copyProperties(courseInfoVo, eduCourse);
        int update = baseMapper.updateById(eduCourse);
        if (update == 0) {
            throw new GuliException(20001, "修改课程信息失败");
        }

        //2.修改描述表
        EduCourseDescription eduCourseDescription = new EduCourseDescription();
        eduCourseDescription.setId(courseInfoVo.getId());
        eduCourseDescription.setDescription(courseInfoVo.getDescription());
        eduCourseDescriptionService.updateById(eduCourseDescription);
    }

    //根据课程id查询课程确认信息
    @Override
    public CoursePublishVo publishCourseInfo(String id) {
        //调用mapper
        //只有baseMapper才能调用自己写的mapper方法
        CoursePublishVo publishCourseInfo = baseMapper.getPublishCourseInfo(id);


        return publishCourseInfo;
    }

    //删除课程
    @Override
    public void removeCourse(String courseId) {

        //1根据课程id删除小节
        eduVideoService.removeVideoByCourseId(courseId);

        //2根据课程id删除章节
        eduChapterService.removeChapterByCourseId(courseId);

        //3根据课程id删除描述
        eduCourseDescriptionService.removeById(courseId);

        //4根据课程id删除课程本身
        int i = baseMapper.deleteById(courseId);
        if (i == 0) {
            throw new GuliException(20001, "删除失败");
        }


    }

    //此注解为将首页前8条热门课程加入redis缓存
    @Cacheable(value = "banner", key = "'selectHotClass'")
    @Override
    //查询前8条热门课程
    public List<EduCourse> selectHotClass() {
        QueryWrapper<EduCourse> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("id");
        wrapper.last("limit 8");
        List<EduCourse> eduList = courseService.list(wrapper);
        return eduList;
    }

    //条件查询带分页查询课程的功能
    @Override
    public Map<String,Object>getCourseFrontList(Page<EduCourse> pageParam, CourseFrontVo courseFrontVo) {
        QueryWrapper<EduCourse> wrapper = new QueryWrapper<>();
        //判断条件值是否为空，不为空拼接
        if (!StringUtils.isEmpty(courseFrontVo.getSubjectParentId()))    //一级分类
        {
            wrapper.eq("subject_parent_id", courseFrontVo.getSubjectParentId());
        }
        if (!StringUtils.isEmpty(courseFrontVo.getSubjectId()))          //二级分类
        {
            wrapper.eq("subject_id", courseFrontVo.getSubjectId());
        }


        if (!StringUtils.isEmpty(courseFrontVo.getBuyCountSort())) {     //关注度
            if (courseFrontVo.getBuyCountSort().equals("1"))         //根据传回来的值是否为1，为1则进行降序排序，不为1则进行升序排序
            {
                wrapper.orderByDesc("buy_count");
//                System.out.println("降序");
            }
            else
            {
                wrapper.orderByAsc("buy_count");
//                System.out.println("升序");
            }
        }


        if (!StringUtils.isEmpty(courseFrontVo.getGmtCreateSort())) {    //最新
            if(courseFrontVo.getGmtCreateSort().equals("1"))
            {
                wrapper.orderByDesc("gmt_create");
//                System.out.println("降序");
            }
            else
            {
                wrapper.orderByAsc("gmt_create");
//                System.out.println("升序");
            }
        }


        if (!StringUtils.isEmpty(courseFrontVo.getPriceSort())) {        //价格
            if (courseFrontVo.getPriceSort().equals("1"))
            {
                wrapper.orderByDesc("price");
//                System.out.println("降序");
            }
            else
            {
                wrapper.orderByAsc("price");
//                System.out.println("升序");
            }
        }



        //把分页数据封装到pageParam对象中来
        baseMapper.selectPage(pageParam, wrapper);

        List<EduCourse> records = pageParam.getRecords();   //每页数据list集合
        long current = pageParam.getCurrent();              //当前页
        long pages = pageParam.getPages();                  //总页数
        long size = pageParam.getSize();                    //每页记录数
        long total = pageParam.getTotal();                  //总记录数
        boolean hasNext = pageParam.hasNext();              //是否有下一页
        boolean hasPrevious = pageParam.hasPrevious();      //是否有上一页

        //把分页数据获取出来，放到map集合
        Map<String,Object> map=new HashMap<>();
        map.put("items", records);
        map.put("current", current);
        map.put("pages", pages);
        map.put("size", size);
        map.put("total", total);
        map.put("hasNext", hasNext);
        map.put("hasPrevious", hasPrevious);
        //map返回
        return map;
    }

    //根据课程id，编写sql语句查询课程信息
    @Override
    public CourseWebVo getBaseCourseInfo(String courseId) {
        //使用自定义mapper编写sql语句
        return baseMapper.getBaseCourseInfo(courseId);
    }


}
